package com.ruoyi.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.oss.config.AliyunConfig;
import com.ruoyi.oss.service.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * OSS服务实现类
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@Service("ossServiceImpl")
public class OssServiceImpl implements IOssService {
    
    private static final Logger log = LoggerFactory.getLogger(OssServiceImpl.class);
    
    @Autowired
    @Qualifier("ossAliyunConfig")
    private AliyunConfig aliyunConfig;
    
    @Override
    public String uploadFile(MultipartFile file) {
        return uploadFile(file, "uploads/");
    }
    
    @Override
    public String uploadFile(MultipartFile file, String uploadPath) {
        OSS ossClient = null;
        try {
            // 检查配置是否正确加载
            log.info("OSS配置信息: region={}, accessKeyId={}, bucket={}", 
                aliyunConfig.getOss().getRegion(),
                aliyunConfig.getOss().getAccessKeyId(),
                aliyunConfig.getOss().getBucket());
            
            if (aliyunConfig.getOss().getAccessKeyId() == null || aliyunConfig.getOss().getAccessKeyId().isEmpty()) {
                throw new RuntimeException("OSS AccessKeyId 未配置");
            }
            
            if (aliyunConfig.getOss().getAccessKeySecret() == null || aliyunConfig.getOss().getAccessKeySecret().isEmpty()) {
                throw new RuntimeException("OSS AccessKeySecret 未配置");
            }
            
            // 构建endpoint URL
            String endpoint = "https://" + aliyunConfig.getOss().getRegion() + ".aliyuncs.com";
            
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(
                endpoint,
                aliyunConfig.getOss().getAccessKeyId(),
                aliyunConfig.getOss().getAccessKeySecret()
            );
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = uploadPath + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "") + extension;
            
            // 上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                aliyunConfig.getOss().getBucket(),
                fileName,
                file.getInputStream()
            );
            
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            
            // 返回文件URL
            return "https://" + aliyunConfig.getOss().getBucket() + "." + aliyunConfig.getOss().getRegion() + ".aliyuncs.com/" + fileName;
            
        } catch (IOException e) {
            log.error("上传文件到OSS失败", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    
    @Override
    public boolean deleteFile(String url) {
        OSS ossClient = null;
        try {
            // 从URL中提取文件名
            String fileName = url.substring(url.indexOf("/", 8) + 1);
            
            // 构建endpoint URL
            String endpoint = "https://" + aliyunConfig.getOss().getRegion() + ".aliyuncs.com";
            
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(
                endpoint,
                aliyunConfig.getOss().getAccessKeyId(),
                aliyunConfig.getOss().getAccessKeySecret()
            );
            
            // 删除文件
            ossClient.deleteObject(aliyunConfig.getOss().getBucket(), fileName);
            return true;
            
        } catch (Exception e) {
            log.error("删除OSS文件失败", e);
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
} 